import React from 'react';
import MSG from '../api/connectMsg';

class CanvasBoard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            backgroundColor: '#ccc',
            colors: ["red", "green", "blue", "yellow"],
            sizes: [20, 12, 6, 2],
            strokeColor: "red",
            strokeSize: 6,
            remarkHeight: 120,
            clearRect: false,

        }
        this._drawObj = null;       //当前画笔状态,\
        this._roomKey = null;       //当前房间key
        this.createDrawColor = this.createDrawColor.bind(this);
        this.createDrawSize = this.createDrawSize.bind(this);
        this.endDraw = this.endDraw.bind(this);
        this.moveDraw = this.moveDraw.bind(this);
        this.startDraw = this.startDraw.bind(this);
    }
    componentWillMount() {
      
    }
    componentDidMount() {
        // alert('componentDidMount');
        this._canvas = document.getElementById('canvas');
        this._ctx = this._canvas.getContext('2d');
        this.update();
        //监听服务器中其他人画画内容.
        window.socket.on(MSG.ADD_DRAW_INFO, rst => {
            //this._drawInfoList.push(rst);
            this.props.pushDrawInfo(rst);
            this.update();
        });
    }
    componentWillUpdate() {
       
    }

    componentDidUpdate(){
        if(this.props.drawInfo != null && this._roomKey !== this.props.drawInfo.key){
            this.update();
        }else{
            console.log('相同');
        }
    }
    componentWillUnmount() {
        //取消监听.
        window.socket.off(MSG.ADD_DRAW_INFO);
    }

    createDrawColor(color) {
        let style = {
            backgroundColor: color,
            color: color
        }
        let span = (
            <span
                key={color}
                className={`mui-badge${color === this.state.strokeColor && !this.state.clearRect ? ' black' : ''}`}
                style={style}
                onClick={() => { this.changeStroke(color) }}
            >1</span>
        )
        return span;
    }
    createDrawSize(size) {
        let style = {
            width: size + 'px',
            height: size + 'px',
            marginTop: (18 - size) / 2 + 'px'
        };
        let span = (
            <div key={size} className="draw-size-body" onClick={() => { this.changeSize(size) }}>
                <div className={`draw-circle ${size === this.state.strokeSize ? ' select' : ''}`}
                    style={style}>
                </div>
            </div>
        )
        return span;
    }
    //切换橡皮擦
    toggleEraser() {
        this.setState((prevState, props) => {
            return {
                clearRect: !prevState.clearRect
            }
        });

    }
    changeStroke(color) {
        this.setState({
            strokeColor: color,
            clearRect: false
        });
    }
    changeSize(size) {
        this.setState({
            strokeSize: size
        });
    }


    endDraw(evt) {
        evt.preventDefault();
        this._canvas.removeEventListener("mousemove", this.moveDraw);
        this._canvas.removeEventListener("mouseup", this.endDraw);

        this.props.addDrawInfo(this._drawObj);
        this._drawObj = null;

    }
    moveDraw(evt) {
        evt.preventDefault();
        var arr = this.getDrawXY(evt);
        this._drawObj.list.push(arr);

        this.update();
    }
    startDraw(evt) {
        evt.preventDefault();
        this._canvas.addEventListener("mousemove", this.moveDraw, false);
        this._canvas.addEventListener("mouseup", this.endDraw, false);

        var arr = this.getDrawXY(evt);
        console.log(arr);
        this._drawObj = {
            color: this.state.strokeColor,
            size: this.state.strokeSize,
            clearRect: this.state.clearRect,
            userName: null,
            list: [arr]
        };
    }
    update() {
        this.clearCanvas();
        var list = this.props.drawInfo.drawInfoList.map(t=>{
            return t;
        });
        for (let i = 0; i < list.length; i++) {
            const draw = list[i];
            this.drawLine(draw);
        }
        this.drawLine(this._drawObj);
    }
    clearCanvas() {
        this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
    }
    drawLine(drawObj) {
        if (drawObj == null || drawObj.list == null) return;
        var ctx = this._ctx;
        var arr = drawObj.list;
        ctx.save();
        ctx.lineWidth = drawObj.size;
        ctx.lineCap = "round";
        ctx.strokeStyle = drawObj.color;
        if (drawObj.clearRect) {
            ctx.globalCompositeOperation = "destination-out";
            //ctx.strokeStyle = this.backGroundColor;
        }
        ctx.beginPath();
        ctx.moveTo(arr[0][0], arr[0][1]);
        for (let s = 1; s < arr.length; s++) {
            const point = arr[s];
            ctx.lineTo(point[0], point[1]);
        }
        ctx.stroke();
        ctx.restore();
    }
    getDrawXY(e) {
        var pageX = e.pageX || e.targetTouches[0].clientX;
        var pageY = e.pageY || e.targetTouches[0].clientY;
        var rect = this.getElementRect();
        pageX -= rect.left;
        pageY -= rect.top;

        var w = this._canvas.width;
        var h = this._canvas.height;

        pageX /= (rect.right - rect.left) / w;
        pageY /= (rect.bottom - rect.top) / h;

        return [pageX, pageY];
    }
    //计算canvas在浏览器上绝对位置(from createjs)
    getElementRect() {
        var bounds;
        var e = this._canvas;
        try {
            bounds = e.getBoundingClientRect();
        } catch (err) {
            // this can fail on disconnected DOM elements in IE9
            bounds = {
                top: e.offsetTop,
                left: e.offsetLeft,
                width: e.offsetWidth,
                height: e.offsetHeight
            };
        }

        var offX =
            (window.pageXOffset || document.scrollLeft || 0) -
            (document.clientLeft || document.body.clientLeft || 0);
        var offY =
            (window.pageYOffset || document.scrollTop || 0) -
            (document.clientTop || document.body.clientTop || 0);

        var styles = window.getComputedStyle
            ? getComputedStyle(e, null)
            : e.currentStyle; // IE <9 compatibility.

        var padL =
            parseInt(styles.paddingLeft, 10) + parseInt(styles.borderLeftWidth, 10);
        var padT = parseInt(styles.paddingTop, 10) + parseInt(styles.borderTopWidth, 10);
        var padR =
            parseInt(styles.paddingRight, 10) + parseInt(styles.borderRightWidth, 10);
        var padB =
            parseInt(styles.paddingBottom, 10) + parseInt(styles.borderBottomWidth, 10);

        // note: in some browsers bounds properties are read only.
        return {
            left: bounds.left + offX + padL,
            right: bounds.right + offX - padR,
            top: bounds.top + offY + padT,
            bottom: bounds.bottom + offY - padB
        };
    }
    render() {
        // console.log('橡皮擦', this.state.clearRect);
        const colors = this.state.colors.map(t => { return this.createDrawColor(t) });
        const sizes = this.state.sizes.map(t => { return this.createDrawSize(t) });

        var obj = (
            <div className="draw">
                <canvas
                    id="canvas"
                    width="1000"
                    height="500"
                    className="draw-context"
                    style={{ backgroundColor: this.state.backgroundColor }}
                    onTouchEnd={this.endDraw}
                    onTouchMove={this.moveDraw}
                    onTouchStart={this.startDraw}
                    onMouseDown={this.startDraw}
                >
                </canvas>
                <div className="draw-tool">
                    <div className="draw-color">
                        {colors}
                    </div>
                    <div className="draw-size">
                        {sizes}
                    </div>
                    <div className="eraser">
                        <button type="button"
                            className={`mui-btn${this.state.clearRect ? ' select' : ''}`}
                            onClick={this.toggleEraser.bind(this)}>橡皮擦
                        </button>
                    </div>
                </div>
            </div>
        );

        return obj;


    }
}



export default CanvasBoard;